#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
优化的趋势预测系统 - 第七步执行模块
专门针对周收益目标(2-3%)的趋势预测优化
"""

import sys
import os
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from real_data_fetcher import RealDataFetcher

class OptimizedTrendPredictor:
    """优化的趋势预测系统 - 专为周收益目标设计"""
    
    def __init__(self):
        self.data_fetcher = RealDataFetcher()
        
        # 预测配置 - 针对周收益优化
        self.prediction_config = {
            'prediction_period': 5,       # 预测5个交易日（1周）
            'weekly_target_return': 0.025, # 周收益目标2.5%
            'confidence_threshold': 0.7,   # 置信度阈值70%
            'risk_control_ratio': 0.03,    # 风险控制比例3%
            'min_data_points': 60,         # 最少需要60个交易日数据
        }
        
        # 多模型权重配置
        self.model_weights = {
            'technical_model': 0.40,       # 技术指标预测40%
            'momentum_model': 0.30,        # 价格动量预测30%
            'volume_model': 0.20,          # 成交量预测20%
            'sentiment_model': 0.10,       # 市场情绪预测10%
        }
        
        # 技术指标参数
        self.technical_params = {
            'ma_short': 5,     # 短期均线
            'ma_long': 20,     # 长期均线
            'rsi_period': 6,   # RSI周期
            'macd_fast': 12,   # MACD快线
            'macd_slow': 26,   # MACD慢线
            'bb_period': 20,   # 布林带周期
        }
        
    def print_header(self, title):
        """打印标题"""
        print(f"\n{'='*80}")
        print(f"🔮 {title}")
        print(f"{'='*80}")
        
    def load_selected_stocks(self, filename):
        """加载优选股票数据"""
        try:
            if os.path.exists(filename):
                df = pd.read_csv(filename)
                print(f"✅ 成功加载优选股票数据: {len(df)} 只")
                return df.to_dict('records')
            else:
                print(f"❌ 文件不存在: {filename}")
                return []
        except Exception as e:
            print(f"❌ 加载优选股票数据失败: {e}")
            return []
    
    def predict_stock_trend(self, stock_info):
        """预测单只股票的一周趋势"""
        try:
            stock_code = stock_info['code']
            stock_name = stock_info['name']
            
            print(f"🔍 预测股票: {stock_code} - {stock_name}")
            
            # 获取历史数据
            historical_data = self.data_fetcher.get_stock_data(stock_code, days=90)
            if historical_data is None or len(historical_data) < self.prediction_config['min_data_points']:
                print(f"   ❌ 历史数据不足: {len(historical_data) if historical_data is not None else 0} 条")
                return None
            
            # 计算技术指标
            tech_indicators = self.calculate_technical_indicators(historical_data)
            
            # 多模型预测
            predictions = {}
            
            # 1. 技术指标预测模型
            predictions['technical'] = self.technical_prediction_model(historical_data, tech_indicators)
            
            # 2. 价格动量预测模型
            predictions['momentum'] = self.momentum_prediction_model(historical_data)
            
            # 3. 成交量预测模型
            predictions['volume'] = self.volume_prediction_model(historical_data)
            
            # 4. 市场情绪预测模型
            predictions['sentiment'] = self.sentiment_prediction_model(historical_data, tech_indicators)
            
            # 综合预测结果
            final_prediction = self.ensemble_predictions(predictions)
            
            # 生成预测报告
            prediction_report = self.generate_prediction_report(
                stock_code, stock_name, historical_data, final_prediction, tech_indicators
            )
            
            return prediction_report
            
        except Exception as e:
            print(f"❌ 预测股票 {stock_info.get('code', 'N/A')} 失败: {e}")
            return None
    
    def calculate_technical_indicators(self, data):
        """计算技术指标"""
        try:
            indicators = {}
            
            # 移动平均线
            indicators['ma5'] = data['close'].rolling(window=self.technical_params['ma_short']).mean()
            indicators['ma20'] = data['close'].rolling(window=self.technical_params['ma_long']).mean()
            
            # RSI
            indicators['rsi'] = self.calculate_rsi(data['close'], self.technical_params['rsi_period'])
            
            # MACD
            macd_data = self.calculate_macd(data['close'], 
                                          self.technical_params['macd_fast'],
                                          self.technical_params['macd_slow'])
            indicators.update(macd_data)
            
            # 布林带
            bb_data = self.calculate_bollinger_bands(data['close'], self.technical_params['bb_period'])
            indicators.update(bb_data)
            
            # 成交量指标
            indicators['volume_ma'] = data['volume'].rolling(window=10).mean()
            indicators['volume_ratio'] = data['volume'] / indicators['volume_ma']
            
            return indicators
            
        except Exception as e:
            print(f"❌ 计算技术指标失败: {e}")
            return {}
    
    def calculate_rsi(self, prices, period):
        """计算RSI指标"""
        try:
            delta = prices.diff()
            gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
            loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
            rs = gain / loss
            rsi = 100 - (100 / (1 + rs))
            return rsi
        except:
            return pd.Series(index=prices.index)
    
    def calculate_macd(self, prices, fast_period, slow_period):
        """计算MACD指标"""
        try:
            ema_fast = prices.ewm(span=fast_period).mean()
            ema_slow = prices.ewm(span=slow_period).mean()
            macd_line = ema_fast - ema_slow
            signal_line = macd_line.ewm(span=9).mean()
            histogram = macd_line - signal_line
            
            return {
                'macd': macd_line,
                'macd_signal': signal_line,
                'macd_histogram': histogram
            }
        except:
            return {'macd': pd.Series(index=prices.index),
                   'macd_signal': pd.Series(index=prices.index),
                   'macd_histogram': pd.Series(index=prices.index)}
    
    def calculate_bollinger_bands(self, prices, period):
        """计算布林带指标"""
        try:
            ma = prices.rolling(window=period).mean()
            std = prices.rolling(window=period).std()
            upper_band = ma + (std * 2)
            lower_band = ma - (std * 2)
            
            return {
                'bb_upper': upper_band,
                'bb_middle': ma,
                'bb_lower': lower_band,
                'bb_width': (upper_band - lower_band) / ma
            }
        except:
            return {'bb_upper': pd.Series(index=prices.index),
                   'bb_middle': pd.Series(index=prices.index),
                   'bb_lower': pd.Series(index=prices.index),
                   'bb_width': pd.Series(index=prices.index)}
    
    def technical_prediction_model(self, data, indicators):
        """技术指标预测模型"""
        try:
            score = 50  # 基础分数
            
            current_price = data['close'].iloc[-1]
            
            # 均线分析
            if not pd.isna(indicators['ma5'].iloc[-1]) and not pd.isna(indicators['ma20'].iloc[-1]):
                ma5_current = indicators['ma5'].iloc[-1]
                ma20_current = indicators['ma20'].iloc[-1]
                
                if current_price > ma5_current > ma20_current:
                    score += 20  # 多头排列
                elif current_price < ma5_current < ma20_current:
                    score -= 20  # 空头排列
            
            # RSI分析
            if not pd.isna(indicators['rsi'].iloc[-1]):
                rsi_current = indicators['rsi'].iloc[-1]
                
                if 30 <= rsi_current <= 70:
                    score += 10  # RSI正常区间
                elif rsi_current < 30:
                    score += 15  # 超卖，可能反弹
                elif rsi_current > 70:
                    score -= 15  # 超买，可能回调
            
            # MACD分析
            if not pd.isna(indicators['macd'].iloc[-1]) and not pd.isna(indicators['macd_signal'].iloc[-1]):
                macd_current = indicators['macd'].iloc[-1]
                signal_current = indicators['macd_signal'].iloc[-1]
                
                if macd_current > signal_current and macd_current > 0:
                    score += 15  # 多头信号
                elif macd_current < signal_current and macd_current < 0:
                    score -= 15  # 空头信号
            
            # 布林带分析
            if not pd.isna(indicators['bb_upper'].iloc[-1]) and not pd.isna(indicators['bb_lower'].iloc[-1]):
                bb_upper = indicators['bb_upper'].iloc[-1]
                bb_lower = indicators['bb_lower'].iloc[-1]
                bb_middle = indicators['bb_middle'].iloc[-1]
                
                if current_price < bb_lower:
                    score += 10  # 价格在下轨，可能反弹
                elif current_price > bb_upper:
                    score -= 10  # 价格在上轨，可能回调
                elif bb_lower < current_price < bb_middle:
                    score += 5   # 价格在下半部分，相对安全
            
            # 限制评分范围
            score = max(0, min(100, score))
            
            return {
                'score': score,
                'confidence': score / 100,
                'signals': self.get_technical_signals(indicators, current_price)
            }
            
        except Exception as e:
            print(f"❌ 技术指标预测失败: {e}")
            return {'score': 50, 'confidence': 0.5, 'signals': []}
    
    def momentum_prediction_model(self, data):
        """价格动量预测模型"""
        try:
            score = 50  # 基础分数
            
            # 计算不同周期的动量
            closes = data['close']
            
            # 5日动量
            momentum_5d = (closes.iloc[-1] - closes.iloc[-6]) / closes.iloc[-6] * 100 if len(closes) >= 6 else 0
            
            # 10日动量
            momentum_10d = (closes.iloc[-1] - closes.iloc[-11]) / closes.iloc[-11] * 100 if len(closes) >= 11 else 0
            
            # 20日动量
            momentum_20d = (closes.iloc[-1] - closes.iloc[-21]) / closes.iloc[-21] * 100 if len(closes) >= 21 else 0
            
            # 动量评分
            if momentum_5d > 0:
                score += min(15, momentum_5d * 3)
            else:
                score += max(-15, momentum_5d * 3)
            
            if momentum_10d > 0:
                score += min(10, momentum_10d * 2)
            else:
                score += max(-10, momentum_10d * 2)
            
            if momentum_20d > 0:
                score += min(10, momentum_20d * 1)
            else:
                score += max(-10, momentum_20d * 1)
            
            # 动量一致性检查
            if momentum_5d > 0 and momentum_10d > 0 and momentum_20d > 0:
                score += 15  # 多周期动量一致向上
            elif momentum_5d < 0 and momentum_10d < 0 and momentum_20d < 0:
                score -= 15  # 多周期动量一致向下
            
            # 限制评分范围
            score = max(0, min(100, score))
            
            return {
                'score': score,
                'confidence': score / 100,
                'momentum_5d': momentum_5d,
                'momentum_10d': momentum_10d,
                'momentum_20d': momentum_20d
            }
            
        except Exception as e:
            print(f"❌ 动量预测失败: {e}")
            return {'score': 50, 'confidence': 0.5, 'momentum_5d': 0, 'momentum_10d': 0, 'momentum_20d': 0}
    
    def volume_prediction_model(self, data):
        """成交量预测模型"""
        try:
            score = 50  # 基础分数
            
            volumes = data['volume']
            closes = data['close']
            
            # 计算成交量移动平均
            volume_ma5 = volumes.rolling(window=5).mean()
            volume_ma10 = volumes.rolling(window=10).mean()
            
            current_volume = volumes.iloc[-1]
            
            # 成交量放大检查
            if not pd.isna(volume_ma5.iloc[-1]):
                volume_ratio_5d = current_volume / volume_ma5.iloc[-1]
                
                if volume_ratio_5d > 1.5:  # 成交量放大50%以上
                    if closes.iloc[-1] > closes.iloc[-2]:  # 价格上涨
                        score += 20  # 量价齐升
                    else:  # 价格下跌
                        score -= 10  # 量增价跌，谨慎
                elif volume_ratio_5d < 0.7:  # 成交量萎缩
                    score -= 5  # 成交量不足
            
            # 成交量趋势分析
            if len(volumes) >= 10:
                recent_volumes = volumes.tail(5)
                earlier_volumes = volumes.tail(10).head(5)
                
                if recent_volumes.mean() > earlier_volumes.mean():
                    score += 10  # 成交量增加
                else:
                    score -= 5   # 成交量减少
            
            # 价量背离检查
            if len(closes) >= 5 and len(volumes) >= 5:
                price_trend = closes.iloc[-1] - closes.iloc[-5]
                volume_trend = volumes.tail(5).mean() - volumes.tail(10).head(5).mean()
                
                if price_trend > 0 and volume_trend < 0:
                    score -= 15  # 价涨量缩，背离
                elif price_trend < 0 and volume_trend > 0:
                    score -= 10  # 价跌量增，背离
            
            # 限制评分范围
            score = max(0, min(100, score))
            
            return {
                'score': score,
                'confidence': score / 100,
                'volume_analysis': self.get_volume_signals(volumes, closes)
            }
            
        except Exception as e:
            print(f"❌ 成交量预测失败: {e}")
            return {'score': 50, 'confidence': 0.5, 'volume_analysis': []}
    
    def sentiment_prediction_model(self, data, indicators):
        """市场情绪预测模型"""
        try:
            score = 50  # 基础分数
            
            # 基于技术指标的情绪分析
            current_price = data['close'].iloc[-1]
            
            # 价格位置分析（相对于近期高低点）
            recent_high = data['high'].tail(20).max()
            recent_low = data['low'].tail(20).min()
            
            if recent_high > recent_low:
                price_position = (current_price - recent_low) / (recent_high - recent_low)
                
                if price_position > 0.8:  # 接近高点
                    score -= 10  # 情绪可能过热
                elif price_position < 0.2:  # 接近低点
                    score += 10  # 情绪可能过冷，存在机会
            
            # 波动率分析
            returns = data['close'].pct_change().dropna()
            if len(returns) >= 10:
                volatility = returns.tail(10).std()
                avg_volatility = returns.std()
                
                if volatility > avg_volatility * 1.5:
                    score -= 5  # 波动率过高，情绪不稳定
                elif volatility < avg_volatility * 0.5:
                    score += 5  # 波动率较低，情绪稳定
            
            # 连续涨跌分析
            price_changes = data['close'].diff().tail(5)
            positive_days = (price_changes > 0).sum()
            negative_days = (price_changes < 0).sum()
            
            if positive_days >= 4:
                score -= 10  # 连续上涨，可能过热
            elif negative_days >= 4:
                score += 5   # 连续下跌，可能存在机会
            
            # 限制评分范围
            score = max(0, min(100, score))
            
            return {
                'score': score,
                'confidence': score / 100,
                'sentiment_indicators': {
                    'price_position': price_position if 'price_position' in locals() else 0.5,
                    'volatility_level': 'normal',
                    'trend_consistency': positive_days - negative_days
                }
            }
            
        except Exception as e:
            print(f"❌ 情绪预测失败: {e}")
            return {'score': 50, 'confidence': 0.5, 'sentiment_indicators': {}}
    
    def ensemble_predictions(self, predictions):
        """集成多个预测模型的结果"""
        try:
            # 加权平均计算最终分数
            final_score = 0
            total_weight = 0
            
            for model_name, weight in self.model_weights.items():
                model_key = model_name.replace('_model', '')
                if model_key in predictions and predictions[model_key]:
                    model_score = predictions[model_key].get('score', 50)
                    final_score += model_score * weight
                    total_weight += weight
            
            if total_weight > 0:
                final_score = final_score / total_weight
            else:
                final_score = 50
            
            # 计算综合置信度
            confidences = []
            for model_name in self.model_weights.keys():
                model_key = model_name.replace('_model', '')
                if model_key in predictions and predictions[model_key]:
                    confidences.append(predictions[model_key].get('confidence', 0.5))
            
            final_confidence = np.mean(confidences) if confidences else 0.5
            
            # 生成预测结果
            if final_score >= 70:
                trend_prediction = '强烈看涨'
                risk_level = '低风险'
            elif final_score >= 60:
                trend_prediction = '温和看涨'
                risk_level = '中风险'
            elif final_score >= 40:
                trend_prediction = '震荡整理'
                risk_level = '中风险'
            elif final_score >= 30:
                trend_prediction = '温和看跌'
                risk_level = '中风险'
            else:
                trend_prediction = '强烈看跌'
                risk_level = '高风险'
            
            return {
                'final_score': final_score,
                'final_confidence': final_confidence,
                'trend_prediction': trend_prediction,
                'risk_level': risk_level,
                'model_scores': {k: v.get('score', 50) for k, v in predictions.items() if v},
                'weekly_return_probability': self.calculate_weekly_return_probability(final_score)
            }
            
        except Exception as e:
            print(f"❌ 集成预测失败: {e}")
            return {
                'final_score': 50,
                'final_confidence': 0.5,
                'trend_prediction': '震荡整理',
                'risk_level': '中风险',
                'model_scores': {},
                'weekly_return_probability': 0.5
            }
    
    def calculate_weekly_return_probability(self, score):
        """计算达到周收益目标的概率"""
        try:
            # 基于预测分数计算达到2-3%周收益的概率
            if score >= 80:
                return 0.85  # 高分数，高概率
            elif score >= 70:
                return 0.75
            elif score >= 60:
                return 0.65
            elif score >= 50:
                return 0.55
            elif score >= 40:
                return 0.45
            elif score >= 30:
                return 0.35
            else:
                return 0.25  # 低分数，低概率
        except:
            return 0.5
    
    def get_technical_signals(self, indicators, current_price):
        """获取技术信号"""
        signals = []
        
        try:
            # 均线信号
            if not pd.isna(indicators['ma5'].iloc[-1]) and not pd.isna(indicators['ma20'].iloc[-1]):
                ma5 = indicators['ma5'].iloc[-1]
                ma20 = indicators['ma20'].iloc[-1]
                
                if current_price > ma5 > ma20:
                    signals.append('多头排列')
                elif current_price < ma5 < ma20:
                    signals.append('空头排列')
            
            # RSI信号
            if not pd.isna(indicators['rsi'].iloc[-1]):
                rsi = indicators['rsi'].iloc[-1]
                if rsi < 30:
                    signals.append('RSI超卖')
                elif rsi > 70:
                    signals.append('RSI超买')
            
            # MACD信号
            if not pd.isna(indicators['macd'].iloc[-1]) and not pd.isna(indicators['macd_signal'].iloc[-1]):
                macd = indicators['macd'].iloc[-1]
                signal = indicators['macd_signal'].iloc[-1]
                
                if macd > signal:
                    signals.append('MACD金叉')
                else:
                    signals.append('MACD死叉')
            
        except:
            pass
        
        return signals
    
    def get_volume_signals(self, volumes, closes):
        """获取成交量信号"""
        signals = []
        
        try:
            current_volume = volumes.iloc[-1]
            avg_volume = volumes.rolling(window=10).mean().iloc[-1]
            
            if current_volume > avg_volume * 1.5:
                if closes.iloc[-1] > closes.iloc[-2]:
                    signals.append('量价齐升')
                else:
                    signals.append('放量下跌')
            elif current_volume < avg_volume * 0.7:
                signals.append('成交量萎缩')
            
        except:
            pass
        
        return signals
    
    def generate_prediction_report(self, stock_code, stock_name, data, prediction, indicators):
        """生成预测报告"""
        try:
            current_price = data['close'].iloc[-1]
            
            # 计算目标价格
            target_return = self.prediction_config['weekly_target_return']
            target_price = current_price * (1 + target_return)
            
            # 计算止损止盈价格
            stop_loss_price = current_price * (1 - self.prediction_config['risk_control_ratio'])
            take_profit_price = current_price * (1 + self.prediction_config['risk_control_ratio'])
            
            # 生成操作建议
            operation_advice = self.generate_operation_advice(prediction)
            
            report = {
                'stock_code': stock_code,
                'stock_name': stock_name,
                'current_price': current_price,
                'target_price': target_price,
                'stop_loss_price': stop_loss_price,
                'take_profit_price': take_profit_price,
                'prediction_score': prediction['final_score'],
                'confidence': prediction['final_confidence'],
                'trend_prediction': prediction['trend_prediction'],
                'risk_level': prediction['risk_level'],
                'weekly_return_probability': prediction['weekly_return_probability'],
                'model_scores': prediction['model_scores'],
                'operation_advice': operation_advice,
                'prediction_period': f"{self.prediction_config['prediction_period']}个交易日",
                'analysis_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            }
            
            return report
            
        except Exception as e:
            print(f"❌ 生成预测报告失败: {e}")
            return None
    
    def generate_operation_advice(self, prediction):
        """生成操作建议"""
        try:
            score = prediction['final_score']
            confidence = prediction['final_confidence']
            
            if score >= 70 and confidence >= 0.7:
                return {
                    'action': '建议买入',
                    'timing': '立即执行',
                    'position_size': '标准仓位',
                    'holding_period': '1周',
                    'risk_control': '严格止损'
                }
            elif score >= 60 and confidence >= 0.6:
                return {
                    'action': '谨慎买入',
                    'timing': '分批建仓',
                    'position_size': '减半仓位',
                    'holding_period': '1周',
                    'risk_control': '密切监控'
                }
            elif score >= 40:
                return {
                    'action': '观望等待',
                    'timing': '等待更好时机',
                    'position_size': '暂不建仓',
                    'holding_period': '继续观察',
                    'risk_control': '保持关注'
                }
            else:
                return {
                    'action': '建议避开',
                    'timing': '暂不参与',
                    'position_size': '空仓',
                    'holding_period': '等待转机',
                    'risk_control': '规避风险'
                }
                
        except Exception as e:
            print(f"❌ 生成操作建议失败: {e}")
            return {
                'action': '观望等待',
                'timing': '等待更好时机',
                'position_size': '暂不建仓',
                'holding_period': '继续观察',
                'risk_control': '保持关注'
            }
    
    def predict_portfolio(self, selected_stocks):
        """批量预测投资组合"""
        try:
            results = []
            
            print(f"🔄 开始批量预测 {len(selected_stocks)} 只股票...")
            
            for i, stock in enumerate(selected_stocks, 1):
                print(f"\n📊 进度: {i}/{len(selected_stocks)}")
                
                prediction_result = self.predict_stock_trend(stock)
                if prediction_result:
                    results.append(prediction_result)
                    
            print(f"\n✅ 批量预测完成，成功预测 {len(results)} 只股票")
            return results
            
        except Exception as e:
            print(f"❌ 批量预测失败: {e}")
            return []
    
    def save_prediction_results(self, results, filename):
        """保存预测结果到CSV"""
        try:
            if not results:
                return False
                
            # 转换为DataFrame
            df_data = []
            for result in results:
                df_data.append({
                    'stock_code': result['stock_code'],
                    'stock_name': result['stock_name'],
                    'current_price': result['current_price'],
                    'target_price': result['target_price'],
                    'prediction_score': result['prediction_score'],
                    'confidence': result['confidence'],
                    'trend_prediction': result['trend_prediction'],
                    'risk_level': result['risk_level'],
                    'weekly_return_probability': result['weekly_return_probability'],
                    'operation_advice': result['operation_advice']['action'],
                    'analysis_time': result['analysis_time']
                })
            
            df = pd.DataFrame(df_data)
            df.to_csv(filename, index=False, encoding='utf-8')
            
            print(f"✅ 预测结果已保存到: {filename}")
            return True
            
        except Exception as e:
            print(f"❌ 保存预测结果失败: {e}")
            return False
    
    def generate_prediction_summary_report(self, results):
        """生成预测汇总报告"""
        try:
            if not results:
                return None
                
            # 统计分析
            total_stocks = len(results)
            high_confidence = sum(1 for r in results if r['confidence'] >= 0.7)
            buy_recommendations = sum(1 for r in results if '买入' in r['operation_advice']['action'])
            
            # 平均指标
            avg_score = np.mean([r['prediction_score'] for r in results])
            avg_confidence = np.mean([r['confidence'] for r in results])
            avg_return_probability = np.mean([r['weekly_return_probability'] for r in results])
            
            report = f"""# 趋势预测系统分析报告

## 📊 预测概况
- 分析时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
- 预测股票数量: {total_stocks}
- 预测周期: {self.prediction_config['prediction_period']}个交易日
- 目标周收益: {self.prediction_config['weekly_target_return']*100:.1f}%

## 🎯 预测结果统计

### 整体表现
- 平均预测分数: {avg_score:.1f}分
- 平均置信度: {avg_confidence:.1%}
- 平均周收益概率: {avg_return_probability:.1%}
- 高置信度股票: {high_confidence}只 ({high_confidence/total_stocks*100:.1f}%)
- 买入建议股票: {buy_recommendations}只 ({buy_recommendations/total_stocks*100:.1f}%)

## 📈 个股预测详情

"""
            
            # 按预测分数排序
            sorted_results = sorted(results, key=lambda x: x['prediction_score'], reverse=True)
            
            for i, result in enumerate(sorted_results, 1):
                report += f"""### {i}. {result['stock_code']} - {result['stock_name']}

**预测指标:**
- 预测分数: {result['prediction_score']:.1f}分
- 置信度: {result['confidence']:.1%}
- 趋势预测: {result['trend_prediction']}
- 风险等级: {result['risk_level']}
- 周收益概率: {result['weekly_return_probability']:.1%}

**价格预测:**
- 当前价格: ¥{result['current_price']:.2f}
- 目标价格: ¥{result['target_price']:.2f}
- 止损价格: ¥{result['stop_loss_price']:.2f}
- 止盈价格: ¥{result['take_profit_price']:.2f}

**操作建议:**
- 建议操作: {result['operation_advice']['action']}
- 执行时机: {result['operation_advice']['timing']}
- 仓位建议: {result['operation_advice']['position_size']}
- 持有周期: {result['operation_advice']['holding_period']}

---

"""
            
            report += f"""## 🎯 投资策略建议

### 高优先级股票 (预测分数≥70)
"""
            high_priority = [r for r in sorted_results if r['prediction_score'] >= 70]
            if high_priority:
                for stock in high_priority:
                    report += f"- **{stock['stock_code']}**: {stock['trend_prediction']} (分数: {stock['prediction_score']:.1f})\n"
            else:
                report += "- 暂无高优先级股票\n"
            
            report += f"""
### 中等优先级股票 (预测分数60-70)
"""
            medium_priority = [r for r in sorted_results if 60 <= r['prediction_score'] < 70]
            if medium_priority:
                for stock in medium_priority:
                    report += f"- **{stock['stock_code']}**: {stock['trend_prediction']} (分数: {stock['prediction_score']:.1f})\n"
            else:
                report += "- 暂无中等优先级股票\n"
            
            report += f"""
### 风险控制建议
1. **仓位管理**: 高分数股票可适当增加仓位，低分数股票减少或观望
2. **止损止盈**: 严格执行3%止损止盈策略
3. **动态调整**: 根据市场变化及时调整预测和仓位
4. **分散投资**: 不要将资金集中在单一股票上

### 总体建议
- 预测系统建议关注 {len(high_priority)} 只高优先级股票
- 建议分配 {buy_recommendations} 只股票进行投资
- 预期周收益概率: {avg_return_probability:.1%}
- 风险控制: 严格执行止损策略

---
*本报告基于技术分析和统计模型生成，仅供参考，投资有风险，决策需谨慎。*
"""
            
            return report
            
        except Exception as e:
            print(f"❌ 生成预测汇总报告失败: {e}")
            return None

if __name__ == "__main__":
    # 简单测试
    predictor = OptimizedTrendPredictor()
    print("✅ 优化趋势预测系统初始化成功")
